<!--  -->
<template>
  <div class='tableMain'>
    <div>
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="姓名">
          <el-input v-model="searchForm.realName" placeholder="请输入姓名" @keyup.enter.native="onSubmit" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.mobile" placeholder='请输入手机号' @keyup.enter.native="onSubmit" clearable />
        </el-form-item>
        <el-form-item label="专属客服">
          <el-select filterable v-model="searchForm.shopUserId" placeholder="请选择客服" style="width: 130px;" @change="onSubmit">
            <el-option v-for="(item, index) in salesData" :key="index" :label="item.personName" :value="item.personId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" icon="Search">查询</el-button>
          <el-button @click="onReset" icon="Refresh">重置</el-button>
          <el-button @click="onExport" icon="Download">导出用户</el-button>
          <el-button @click="BatchReplacement" icon="Edit">批量更换客服</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table :data="tableData" v-loading="loading" @selection-change="handleSelectionChange" size="small" style="width: 100%" border stripe>
      <el-table-column type="selection" width="55" fixed="left" align="center"></el-table-column>
      <el-table-column prop="userId" label="用户标识" width="80" align="center" />
      <!-- <el-table-column prop="avatarUrl" label="头像" align="center" width="60">
        <template #default="scope">
          <el-avatar shape="square" :size="size" :src="scope.row.avatarUrl" />
        </template>
      </el-table-column> -->
      <el-table-column prop="nickName" label="昵称" width="120" align="center"></el-table-column>
      <el-table-column prop="gender" label="性别" width="80" align="center">
        <template #default="scope">
          <el-tag effect="dark" :type="scope.row.gender == 0 ? 'danger' : ''"> {{ scope.row.gender == 0 ? '女' :
            scope.row.gender === 1 ? '男' : '未知' }} </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="realName" label="姓名" width="80" align="center"></el-table-column>
      <el-table-column prop="mobile" label="手机号" width="120" align="center"></el-table-column>
      <el-table-column prop="userBalance" width="100" align="center" label="用户余额">
        <template #default="scope">
          <span v-if="scope.row.userBalance">￥{{ scope.row.userBalance }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="salesPersonName" label="专属客服" width="80" align="center"></el-table-column>
      <!-- <el-table-column prop="varirty" label="主营品种" width="180"></el-table-column> -->
      <el-table-column prop="area" label="经营地区"></el-table-column>
      <!-- <el-table-column prop="acreage" label="种植面积"></el-table-column> -->
      <el-table-column prop="createTime" label="注册时间" width="150" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status === 20 ? 'success' : 'danger'">
            {{ scope.row.statusTxt }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="isDelete" label="是否删除">
        <template #default="scope">
          <el-tag :type="scope.row.isDelete === 0 ? 'success' : 'danger'">
            {{ scope.row.isDelete === 0 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column> -->
      <el-table-column prop="cz" label="操作" width="220">
        <template #default="scope">
          <p>
            <el-button type="text" size="small" @click="handlerView(scope.$index, scope.row)" icon="View">查看</el-button>
            <el-button type="text" size="small" v-if="scope.row.status == 10" @click="auditClick(scope.row)" icon="Promotion">审核</el-button>
            <el-button type="text" size="small" @click="onUserCashOut(scope.row)" style="color:red" icon="Coin">变更余额</el-button>
          </p>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination background @current-change="handlerCurrentChange" :page-sizes="[10, 20, 50, 100]" :page-size="defaultPageSize" :current-page="searchForm.pageIndex" layout="total, prev, pager, next, jumper" :total="totalCount"></el-pagination>
    </div>
    <!-- 更换客服 -->
    <el-dialog v-model="dialogVisible" title="更换客服" width="500" :before-close="handleClose">
      <el-select filterable v-model="selectUser" placeholder="请选择客服" style="width: 100%;">
        <el-option v-for="(item, index) in salesData" :key="index" :label="item.personName" :value="item.personId"></el-option>
      </el-select>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" icon="Close">关闭</el-button>
          <el-button type="primary" @click="onChangeSale" icon="Edit">确定更换</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog title="小程序注册审核" v-model="auditFromDrawer" width="30%">
      <el-form :model="auditFrom" ref="auditFrom" label-width="80px" class="demo-form-inline">
        <el-row>
          <el-col :span="24">
            <el-form-item label="审批结果" prop="auditStatus" :rules="[ { required: true, message: '审批结果不能为空' } ]">
              <el-select placeholder="请选择审批结果" v-model="auditFrom.auditStatus">
                <el-option v-for="(item, index) in auditList" :key="index" :label="item.name" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="审核意见" prop="auditAdvice" :rules="[ { required: true, message: '审核意见不能为空' } ]">
              <el-input v-model="auditFrom.auditAdvice" type="textarea" placeholder="请输入审核意见" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="dialog-footer">
        <el-button @click="auditFromDrawer = false">取消</el-button>
        <el-button type="primary" :loading="auditSaveLoading" @click="auditSave">提交</el-button>
      </div>
    </el-dialog>
    <!-- 变更余额 -->
    <el-dialog title="变更余额" v-model="rowOrderAuditShow" width="30%" :before-close="handleClose">
      <div style="margin-bottom: 40px;">
        <p style="margin-bottom: 15px;">
          <span style="color: red;">*</span>变更余额:
          <el-input style="width: 60%;" placeholder="请输入变更余额" type="number" v-model="OrderAuditForm.balance" />
        </p>
        <p>
          <span style="color: red;">*</span>变更原因:
          <el-input style="width: 60%;" placeholder="请输入变更原因" type="textarea" v-model="OrderAuditForm.reason" />
        </p>
      </div>
      <div style="text-align: center;">
        <el-button type="primary" @click="rowOrderAuditSave()" v-loading="rowLoading">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import UserApi from '@/api/user'
import SalesApi from '@/api/sales.js'
import ProductApi from '@/api/product.js';
import { ElMessage } from 'element-plus'
import { defaultPageSize } from '@/utils/table.js'
export default {
  name: '',
  props: {
    tabType: {
      type: Number,
      default: ''
    }
  },
  components: {},
  data() {
    return {
      rowData: {},
      rowLoading: false,
      onUserCashRow: {},
      auditFrom: {},
      auditFromDrawer: false,
      auditSaveLoading: false,
      multipleSelection: [],
      salesData: [],
      selectUser: '',
      dialogVisible: false,
      rowOrderAuditShow: false,
      OrderAuditForm: {},
      loading: false,
      totalCount: 0,
      tableData: [

      ],
      // AUDIT("审批中", 10),
      // NORMAL("正常", 20),
      // DISABLE("禁用", 30),
      // REFUSE("审批拒绝",40),
      statusList: [
        { value: '10', name: '审批中' },
        { value: '20', name: '正常' },
        { value: '30', name: '禁用' },
        { value: '40', name: '审批拒绝' },
      ],
      auditList: [
        { value: '10', name: '同意' },
        { value: '20', name: '拒绝' },
      ],
      searchForm: {
        userType: 1,
        userId: '',
        status: '',
        realName: '',
        rangeTime: '',
        mobile: '',
        pageIndex: 1,
        pageSize: 10,
        startDate: '',
        endDate: '',
        shopUserId: ''
      }
    };
  },
  computed: {},
  watch: {
    tabType: {
      deep: true,
      immediate: true,
      handler(n, v) {

        this.loadTableData(n)
      }
    }
  },
  methods: {
    auditClick(row) {
      this.rowData = row;
      this.auditFromDrawer = true;
    },
    onUserCashOut(row) {
      this.rowOrderAuditShow = true;
      this.onUserCashRow = row;
    },
    rowOrderAuditSave() {
      if (!this.OrderAuditForm.balance) {
        ElMessage.warning('请输入变更余额')
        return;
      }
      if (!this.OrderAuditForm.reason) {
        ElMessage.warning('请输入变更理由')
        return;
      }
      let Obj = {
        userId: this.onUserCashRow.userId,
        ...this.OrderAuditForm
      }
      this.rowLoading = true
      UserApi.userCashOut(Obj).then(result => {
        this.rowLoading = false
        const { code, msg } = result
        if (code === 1) {
          ElMessage.success(msg)
          this.rowOrderAuditShow = false;
          this.loadTableData(this.tabType)
        } else {
          ElMessage.error(msg)
        }
      }).catch(error => {
        this.rowLoading = false
      })
    },
    auditSave() {
      this.$refs['auditFrom'].validate((valid) => {
        if (valid) {
          this.auditSaveLoading = true;
          this.auditFrom['userId'] = this.rowData.userId
          ProductApi.userAudit(this.auditFrom).then(res => {
            const { code, data } = res;
            if (code == 1) {
              this.auditFromDrawer = false;
              this.loadTableData();
              ElMessage({
                message: '提交成功',
                type: 'success'
              });
            }
            this.auditSaveLoading = false
          }).catch(e => {
            this.auditSaveLoading = false

          })
        }
      });


    },
    onExport() {

      UserApi.exportUser()
        .then(res => {
          const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
          const url = window.URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.href = url
          const fdate = new Date()
          const perx = `${fdate.getFullYear()}-${fdate.getMonth() + 1}-${fdate.getDate()}`
          a.download = perx + '用户列表.xlsx'
          a.click()
          setTimeout(() => {
            a.remove()
          }, 1000)
        })
    },
    BatchReplacement() {
      if (!this.multipleSelection.length) {
        return ElMessage.warning('请选择数据');
      }
      this.dialogVisible = true
      this.loadAllSales();
    },
    onChangeSale() {
      UserApi.changeSalesPerson({
        "userIdList": this.multipleSelection.map(val => val.userId),
        "salesPersonId": this.selectUser
      }).then(res => {
        const { code, data, msg } = res;
        if (code == 1) {
          ElMessage.success(msg)
          this.dialogVisible = false;
          this.loadTableData(this.searchForm.userType)
        }
      })
    },
    loadAllSales() {
      const $this = this
      SalesApi.getAllSales()
        .then(result => {
          const { code, data } = result
          if (code === 1) {
            const arrys = []
            data.forEach(item => {
              arrys.push({
                personId: item.shopUserId,
                personName: item.realName
              })
            })
            $this.salesData = arrys
          }
        }
        )
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    loadTableData(type) {
      this.loading = true
      this.searchForm.userType = type
      const $this = this
      UserApi.getUserList($this.searchForm)
        .then(result => {
          $this.loading = false
          const { code, data } = result
          if (code === 1) {
            const { total, records } = data
            $this.totalCount = total
            $this.tableData = records
          }
          console.log('rsult'.result)
        })
    },
    handlerCurrentChange(current) {
      this.searchForm.pageIndex = current
      this.loadTableData(this.tabType)
    },
    onSubmit() {
      const range = this.searchForm.rangeTime
      if (range && range.length > 0) {
        this.searchForm.startDate = range[0]
        this.searchForm.endDate = range[1]
      } else {
        this.searchForm.startDate = ''
        this.searchForm.endDate = ''
      }
      console.log('searchForm.rangeTime', this.searchForm.rangeTime)
      this.loadTableData(this.tabType)
    },
    onReset(){
      this.searchForm.realName = null;
      this.searchForm.mobile = null;
      this.searchForm.shopUserId = null;
      this.searchForm.pageIndex = 1;
      this.searchForm.pageSize = 10;
      this.loadTableData(this.tabType)
    },
    handlerView(index, row) {
      this.$router.push({
        path: '/sysuser/components/UserDetai',
        query: {
          id: row.userId
        }
      })
      console.log('index', index, 'row', row)
    }
  },
  created() {
    this.loadAllSales();

  },
  mounted() {

  },
}
</script>
<style scoped></style>